package cn.com.libertymutual.sp.service.impl;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.core.des.Base64Encoder;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import cn.com.libertymutual.core.redis.util.RedisUtils;
import cn.com.libertymutual.core.security.encoder.Md5PwdEncoder;
import cn.com.libertymutual.core.util.Constants;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.core.zxing.LogoConfig;
import cn.com.libertymutual.core.zxing.Zxing;
import cn.com.libertymutual.sp.bean.TbSpExclusiveProduct;
import cn.com.libertymutual.sp.bean.TbSpProduct;
import cn.com.libertymutual.sp.bean.TbSpShare;
import cn.com.libertymutual.sp.bean.TbSpStoreProduct;
import cn.com.libertymutual.sp.bean.TbSpUser;
import cn.com.libertymutual.sp.dao.ProductDao;
import cn.com.libertymutual.sp.dao.ShareDao;
import cn.com.libertymutual.sp.dao.StoreProductDao;
import cn.com.libertymutual.sp.dao.TbSpExclusiveProductDao;
import cn.com.libertymutual.sp.dao.UserDao;
import cn.com.libertymutual.sp.dto.UserDto;
import cn.com.libertymutual.sp.service.api.ShopService;
import cn.com.libertymutual.sp.service.api.SmsService;
import cn.com.libertymutual.sp.service.api.ZxingQrCodeService;
import cn.com.libertymutual.sys.service.api.ISequenceService;

@Service("ZxingQrCodeService")
@RefreshScope // 刷新配置无需重启服务
public class ZxingQrCodeServiceImpl implements ZxingQrCodeService {

	/** 导出二维码相对路径 */
	@Value("${qrcode.filePath}")
	private String filePath;

	private Logger log = LoggerFactory.getLogger(getClass());
	@Autowired
	private UserDao userDao;
	@Resource
	private SmsService smsService;
	@Resource
	private ShopService shopService;
	@Autowired
	private ISequenceService iSequenceService;
	@Autowired
	private ShareDao shareDao;
	@Autowired
	private StoreProductDao storeProductDao;
	@Autowired
	private ProductDao productDao;
	@Autowired
	private TbSpExclusiveProductDao exclusiveProductDao;
	@Resource
	private RedisUtils redis;
	@Resource
	private RestTemplate restTemplate;

	private String fileType = "png";// 图片类型

	@Override
	public ServiceResult registerZxingQrCode(HttpServletRequest request, HttpServletResponse response, String userCode, String shareUrl,
			String userHeadUrl, String fileType) throws Exception {
		ServiceResult sr = new ServiceResult("二维码创建失败", ServiceResult.STATE_APP_EXCEPTION);
		// filePath = "F:\\imgDemo\\";// Windows系统测试地址

		if (StringUtils.isBlank(userCode)) {
			sr.setAppFail("账户登录超时");
			return sr;
		}

		// TbSpUser user = userDao.findByUserCode(userCode);
		// if(user==null) {
		// sr.setAppFail("账户不存在");
		// return sr;
		// }

		File dirPath = new File(filePath);
		log.info("二维码目录=================================是否存在：" + (dirPath.exists()));
		if (!dirPath.exists()) {
			boolean df = dirPath.mkdirs();
			log.info("创建零时二维码目录=================================结果：" + df);
		}

		if (StringUtils.isBlank(fileType) || fileType.length() > 5) {
			fileType = "jpg";// png会导致图片失色（黑白）
		}
		// ServletOutputStream out = response.getOutputStream();
		try {
			// width:图片完整的宽;height:图片完整的高
			// 因为要在二维码下方附上文字，所以把图片设置为长方形（高大于宽）
			int width = 400;
			int height = 460;

			String imgName = "img_" + userCode + "." + fileType;

			MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
			Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
			// 设置UTF-8， 防止中文乱码
			hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
			// 设置二维码四周白色区域的大小
			hints.put(EncodeHintType.MARGIN, 1);
			// 设置二维码的容错性
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

			// 画二维码，记得调用multiFormatWriter.encode()时最后要带上hints参数，不然上面设置无效
			BitMatrix bitMatrix = multiFormatWriter.encode(shareUrl, BarcodeFormat.QR_CODE, width, height, hints);
			Path path = FileSystems.getDefault().getPath(filePath, imgName);
			// 开始画二维码
			MatrixToImageWriter.writeToPath(bitMatrix, fileType, path);

			// // 开始画二维码
			// MatrixToImageConfig config = new MatrixToImageConfig(onColor, offColor);
			// // 获取图片
			// BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix,
			// config);
			//
			// Graphics2D g2d = bufferedImage.createGraphics();

			// logo
			String logoname = "logo_" + userCode + "." + fileType;

			if (StringUtils.isNotBlank(userHeadUrl)) {
				// qrcFile用来存放生成的二维码图片（无logo，无文字）
				File qrcFile = new File(filePath, imgName);

				Zxing.download(userHeadUrl, logoname, filePath);// filePath
				// 读取Logo图片
				File logoFile = new File(filePath + logoname);

				if (!qrcFile.isFile()) {
					log.info("qrcFile not find !：{}", "\nLogo");
				}
				if (!logoFile.isFile()) {
					log.info("logoFile not find !：{}", "\nLogo");
				}

				/**
				 * 读取二维码图片，并构建绘图对象
				 */
				BufferedImage qrcFileImage = ImageIO.read(qrcFile);
				Graphics2D g2d = qrcFileImage.createGraphics();

				/**
				 * 读取Logo图片
				 */
				BufferedImage logo = ImageIO.read(logoFile);

				// 在二维码中加入图片
				LogoConfig logoConfig = new LogoConfig(); // LogoConfig中设置Logo的属性
				int widthLogo = qrcFileImage.getWidth() / logoConfig.getLogoPart();
				int heightLogo = qrcFileImage.getWidth() / logoConfig.getLogoPart(); //
				// 保持二维码是正方形的

				// 计算图片放置位置
				int x = (qrcFileImage.getWidth() - widthLogo) / 2;
				int y = (qrcFileImage.getHeight() - heightLogo) / 2;

				// 开始绘制图片
				g2d.drawImage(logo, x, y, widthLogo, heightLogo, null);
				g2d.drawRoundRect(x, y, widthLogo, heightLogo, 10, 10);
				g2d.setStroke(new BasicStroke(logoConfig.getBorder()));
				g2d.setColor(logoConfig.getBorderColor());
				g2d.drawRect(x, y, widthLogo, heightLogo);
				g2d.dispose();

				// 输出
				ImageIO.write(qrcFileImage, fileType, new File(filePath + logoname));

				// bufferImage->base64
				ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
				ImageIO.write(qrcFileImage, fileType, outputStream);
				String base64Img = "data:image/" + fileType + ";base64," + Base64Encoder.encode(outputStream.toByteArray());

				sr.setSuccess();
				sr.setResult(base64Img);

				// 删除零时保存的头像文件
				if (StringUtils.isNotBlank(userHeadUrl)) {
					Zxing.deleteFile(new File(filePath + logoname));
				}
			}
			// 删除零时保存的二维码文件
			Zxing.deleteFile(new File(filePath + imgName));
		} catch (Exception e) {
			sr.setAppFail("系统异常：" + e.toString());
			e.printStackTrace();
		}
		return sr;
	}

	public ServiceResult shareZxingQrCode(HttpServletRequest request, HttpServletResponse response, String userCode, String shareUrl,
			String userHeadUrl, String productCName, Integer fontSize, String fileType) throws Exception {

		ServiceResult sr = new ServiceResult("二维码创建失败", ServiceResult.STATE_APP_EXCEPTION);
		if (StringUtils.isBlank(fileType) || fileType.length() > 5) {
			fileType = "jpg";// png会导致图片失色（黑白）
		}
		// ServletOutputStream out = response.getOutputStream();
		try {
			// width:图片完整的宽;height:图片完整的高
			// 因为要在二维码下方附上文字，所以把图片设置为长方形（高大于宽）
			int width = 400;
			int height = 460;

			int onColor = 0xFF000000; // 前景色
			int offColor = 0xFFFFFFFF; // 背景色

			String imgName = "img_" + userCode + "." + fileType;
			// filePath = "F:\\imgDemo\\";

			MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
			Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
			// 设置UTF-8， 防止中文乱码
			hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
			// 设置二维码四周白色区域的大小
			hints.put(EncodeHintType.MARGIN, 1);
			// 设置二维码的容错性
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

			// 画二维码，记得调用multiFormatWriter.encode()时最后要带上hints参数，不然上面设置无效
			BitMatrix bitMatrix = multiFormatWriter.encode(shareUrl, BarcodeFormat.QR_CODE, width, height, hints);
			Path path = FileSystems.getDefault().getPath(filePath, imgName);
			// 开始画二维码
			MatrixToImageWriter.writeToPath(bitMatrix, fileType, path);

			// // 开始画二维码
			// MatrixToImageConfig config = new MatrixToImageConfig(onColor, offColor);
			// // 获取图片
			// BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix,
			// config);
			//
			// Graphics2D g2d = bufferedImage.createGraphics();

			// logo
			String logoname = "logo_" + userCode + "." + fileType;

			if (StringUtils.isNotBlank(userHeadUrl)) {
				// qrcFile用来存放生成的二维码图片（无logo，无文字）
				File qrcFile = new File(filePath, imgName);

				Zxing.download(userHeadUrl, logoname, filePath);// filePath
				// 读取Logo图片
				File logoFile = new File(filePath + logoname);

				if (!qrcFile.isFile()) {
					log.info("qrcFile not find !：{}", "\nLogo");
				}
				if (!logoFile.isFile()) {
					log.info("logoFile not find !：{}", "\nLogo");
				}

				/**
				 * 读取二维码图片，并构建绘图对象
				 */
				BufferedImage qrcFileImage = ImageIO.read(qrcFile);
				Graphics2D g2d = qrcFileImage.createGraphics();

				/**
				 * 读取Logo图片
				 */
				BufferedImage logo = ImageIO.read(logoFile);

				// 在二维码中加入图片
				LogoConfig logoConfig = new LogoConfig(); // LogoConfig中设置Logo的属性
				int widthLogo = qrcFileImage.getWidth() / logoConfig.getLogoPart();
				int heightLogo = qrcFileImage.getWidth() / logoConfig.getLogoPart(); //
				// 保持二维码是正方形的

				// 计算图片放置位置
				int x = (qrcFileImage.getWidth() - widthLogo) / 2;
				int y = (qrcFileImage.getHeight() - heightLogo) / 2;

				// 开始绘制图片
				g2d.drawImage(logo, x, y, widthLogo, heightLogo, null);
				g2d.drawRoundRect(x, y, widthLogo, heightLogo, 10, 10);
				g2d.setStroke(new BasicStroke(logoConfig.getBorder()));
				g2d.setColor(logoConfig.getBorderColor());
				g2d.drawRect(x, y, widthLogo, heightLogo);
				g2d.dispose();

				// 输出
				ImageIO.write(qrcFileImage, fileType, new File(filePath + logoname));
			}

			// 文字
			if (StringUtils.isNotBlank(productCName)) {
				BufferedImage newImageBuffer = null;
				if (StringUtils.isNotBlank(userHeadUrl)) {
					newImageBuffer = ImageIO.read(new File(filePath, logoname));// 读取已画Logo后的文件
				} else {
					newImageBuffer = ImageIO.read(new File(filePath, imgName));// 读取已画的二维码文件
				}
				if (newImageBuffer == null) {
					log.info("File not find !：{}", "\n文字");
					Preconditions.checkNotNull(newImageBuffer == null, "二维码图像为空");
					return null;
				}
				Graphics2D g2d = newImageBuffer.createGraphics();
				// // 画原图
				// g2d.drawImage(src, 0, 0, imageW, imageH, null);

				if (fontSize == null || fontSize <= 0) {
					fontSize = 30;// 字体大小
				}
				// y开始的位置：图片高度-（图片高度-图片宽度）/2
				int startY = height - 10;

				g2d.setColor(Color.BLACK);
				Font font = new Font("黑体", Font.BOLD, fontSize);
				g2d.setFont(font);
				g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

				// 计算文字长度，计算居中的x点坐标
				FontMetrics fm = g2d.getFontMetrics(font);
				int textWidth = fm.stringWidth(productCName);

				// 计算文字开始的位置
				int widthX = (width - textWidth) / 2;

				log.info("widthX ====startY:{}{}", widthX, startY);
				g2d.drawString(productCName, widthX, startY);
				g2d.dispose();

				// 输出
				FileOutputStream out = new FileOutputStream(filePath + imgName);
				ImageIO.write(newImageBuffer, fileType, out);
			}

			/**
			 * 最后读取图片
			 */

			// qrcFile用来存放生成的二维码图片（无logo，无文字）
			File qrcFile = new File(filePath, imgName);
			if (!qrcFile.isFile()) {
				log.info("last qrcFile not find !：{}", "\n最后读取图片");
			}
			/**
			 * 读取二维码图片，并构建绘图对象
			 */
			BufferedImage bufferedImage = ImageIO.read(qrcFile);

			// bufferImage->base64
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			ImageIO.write(bufferedImage, fileType, outputStream);
			String base64Img = "data:image/" + fileType + ";base64," + Base64Encoder.encode(outputStream.toByteArray());

			sr.setSuccess();
			sr.setResult(base64Img);

			// 删除零时保存的二维码文件
			Zxing.deleteFile(new File(filePath + imgName));
			// 删除零时保存的头像文件
			if (StringUtils.isNotBlank(userHeadUrl)) {
				Zxing.deleteFile(new File(filePath + logoname));
			}
			// 删除零时保存的二维码文件
			if (StringUtils.isNotBlank(productCName)) {
				Zxing.deleteFile(new File(filePath + imgName));
			}
		} catch (Exception e) {
			sr.setAppFail("系统异常：" + e.toString());
			e.printStackTrace();
		}
		return sr;
	}

	@Override
	public ServiceResult findUsers(HttpServletRequest request, HttpServletResponse response, String code, Integer s_userid, Integer e_userid)
			throws Exception {
		ServiceResult sr = new ServiceResult();
		sr.setAppFail("查询失败");

		if (StringUtils.isNotBlank(code) && code.equals("test_test")) {

			List<TbSpUser> users = userDao.findByGTId(s_userid, e_userid);
			if (CollectionUtils.isNotEmpty(users)) {
				sr.setResult(users);
				sr.setSuccess();

				// 二维码表示的内容
				// String content =
				// "https://uat-lm.libertymutual.com.cn/sticcxb/#/sticcxb/details?&shareId=4a2d38565109c109e3ca0fc2e65f2c69&pro=177";
				// "https://uat-lm.libertymutual.com.cn/sticcxb/#/sticcxb/";
				String domainName = "https://" + request.getServerName() + "/sticcxb/#sticcxb/";
				// 存放logo的文件夹
				// String filePath = "F://imgDemo//";

				TbSpUser user = null;
				TbSpProduct product = null;
				for (int i = 0; i < users.size(); i++) {
					user = users.get(i);
					List<TbSpStoreProduct> storeProducts = storeProductDao.findUserCode(user.getUserCode());
					for (TbSpStoreProduct storeProduct : storeProducts) {
						product = productDao.findById(storeProduct.getProductId()).get();
						storeProduct.setProductName(product.getProductCname());

						String content = domainName;// 默认地址
						// 加密分享ID
						Md5PwdEncoder md5PwdEncoder = new Md5PwdEncoder();
						String shareId = md5PwdEncoder.encodePassword(user.getUserCode() + ":1");
						// 分享地址
						content += "details?&shareId=" + shareId + "&pro=" + product.getId();
						// 文件路径名
						String fileName = user.getMobile() + "-" + product.getProductCname() + "." + fileType;

						// width:图片完整的宽;height:图片完整的高
						// 因为要在二维码下方附上文字，所以把图片设置为长方形（高大于宽）
						int width = 400;
						int height = 460;
						// String logoFullName = "F://imgDemo//logo//logo." + fileType;
						// String logoFullName = domainName + "upload/assets/x3/logo." + fileType;
						String logoFullName = "";

						Zxing.wirteImg(content, filePath, fileName, fileType, logoFullName,
								new String[] { user.getMobile(), product.getProductCname() }, width, height);
					}
					user.setStoreProducts(storeProducts);

					log.info("数据：{}", "\n" + JSON.toJSONString(user));
				}
			}
		} else {
			sr.setResult("禁止访问");
			return sr;
		}
		return sr;
	}

	@Transactional(propagation = Propagation.REQUIRED) // 事务
	@Modifying(clearAutomatically = true) // @Modifying注解需要使用clearAutomatically=true，同一接口更新后立即查询获得更新后的数据,默认false查询还是更新前的数据
	@Override
	public ServiceResult createUsers(HttpServletRequest request, HttpServletResponse response, String code, String productids) throws Exception {
		ServiceResult sr = new ServiceResult();
		sr.setAppFail("注册失败");

		long stime = System.currentTimeMillis();

		Pattern p = Pattern.compile(Constants.REGEX_SPECIALCHARACTERS_CODE);
		Matcher m = p.matcher(productids);
		if (StringUtils.isBlank(productids) || m.find()) {
			sr.setResult("编码不能包含特殊字符");
			return sr;
		}
		List<Integer> idlists = new ArrayList<>();
		List<String> lists = Arrays.asList(productids.split(","));
		for (int i = 0; i < lists.size(); i++) {
			String str = lists.get(i);
			Integer num = Integer.parseInt(str);
			if (num > 0) {
				idlists.add(num);
			}
		}
		if (CollectionUtils.sizeIsEmpty(idlists)) {
			sr.setResult("参数转换失败");
			return sr;
		}

		String domainName = "https://" + request.getServerName() + "/sticcxb/";
		// 存放logo的文件夹
		// String filePath = "F://imgDemo//";

		// 最终用户
		List<TbSpUser> users = new ArrayList<>();

		if (StringUtils.isNotBlank(code) && code.equals("test_test")) {
			// 用户基本数据
			JSONArray array = JSONArray.parseArray(userJsons);
			List<UserDto> list = array.toJavaList(UserDto.class);

			// 需要上到店铺的产品
			List<TbSpProduct> products = productDao.findInIds(idlists);

			if (CollectionUtils.sizeIsEmpty(products)) {
				sr.setResult("对应产品查询为空，无法执行");
				return sr;
			}

			TbSpUser user = new TbSpUser();
			Date nowTime = new Date();
			for (int i = 0; i < list.size(); i++) {
				UserDto dto = list.get(i);

				user.setUserCode(iSequenceService.getUserCodeSequence("BS"));
				user.setHeadUrl("upload/userHeadImg/default/headImgDefault.jpg");

				user.setMobile(dto.getMobile());

				String pwd = dto.getPassword();
				// 加密密码
				Md5PwdEncoder md5PwdEncoder = new Md5PwdEncoder();
				pwd = md5PwdEncoder.encodePassword(pwd);

				user.setPassword(pwd);
				user.setUserName(dto.getUserName());
				user.setNickName(dto.getNickName());
				user.setIdNumber(dto.getIdNumber());

				user.setStoreFlag(dto.getStoreFlag());
				if (StringUtils.isBlank(dto.getAgrementName())) {
					user.setUserType("2");
				} else {
					user.setUserType("3");// 专业代理
				}
				user.setBranchCode(dto.getBranchCode());
				user.setAgrementNo(dto.getAgrementNo());
				user.setAgrementName(dto.getAgrementName());
				user.setChannelCode(dto.getChannelCode());
				user.setChannelName(dto.getChannelName());

				user.setSaleCode(dto.getSaleCode());
				user.setSaleName(dto.getSaleName());

				user.setRegisteDate(new Timestamp(nowTime.getTime()));
				user.setLastloginDate(new Timestamp(nowTime.getTime()));

				user = userDao.save(user);
				users.add(user);

				this.saveShare(user.getUserCode());

				try {
					// 店铺上架产品
					if (CollectionUtils.isNotEmpty(products)) {
						for (int j = 0; j < products.size(); j++) {
							TbSpProduct product = products.get(j);
							// 批量上产品
							TbSpStoreProduct storeProduct = new TbSpStoreProduct();
							storeProduct.setUserCode(user.getUserCode());
							storeProduct.setProductId(product.getId());
							storeProduct.setRiskSerialNo(j);
							storeProduct.setSerialNo(j);
							storeProduct.setIsShow("1");
							storeProductDao.save(storeProduct);

							if (product.getId() != 115) {// 115=宠物保
								// 批量设置为专属产品
								TbSpExclusiveProduct exclusiveProduct = new TbSpExclusiveProduct();
								exclusiveProduct.setProductId(product.getId());
								exclusiveProduct.setUserCode(user.getUserCode());

								exclusiveProductDao.save(exclusiveProduct);
							}

							String content = domainName + "#/sticcxb/";// 默认地址
							// 加密分享ID
							String shareId = md5PwdEncoder.encodePassword(user.getUserCode() + ":1");
							// 分享地址
							content += "details?&shareId=" + shareId + "&pro=" + product.getId();
							// 文件路径名
							String fileName = user.getMobile() + " - " + product.getId() + "." + fileType;

							// width:图片完整的宽;height:图片完整的高
							// 因为要在二维码下方附上文字，所以把图片设置为长方形（高大于宽）
							int width = 400;
							int height = 460;
							// String logoFullName = "F://imgDemo//logo//logo." + fileType;
							// String logoFullName = domainName + "upload/assets/x3/logo." + fileType;
							String logoFullName = "";

							Zxing.wirteImg(content, filePath, fileName, fileType, logoFullName,
									new String[] { user.getMobile(), product.getProductCname() }, width, height);
						}
					}
				} catch (Exception e) {
					log.info("\\n出错了{}", e.toString());
					e.printStackTrace();
				}
				user = new TbSpUser();
				log.info("数据：{}", "\n" + JSON.toJSONString(user));
			}

			HashMap<String, Object> hashMap = Maps.newHashMap();
			hashMap.put("users", users);
			hashMap.put("msg", "所有产品二维码文件已输出到目录：" + filePath);
			sr.setResult(hashMap);
			sr.setSuccess();
		} else {
			sr.setResult("禁止访问");
			return sr;
		}
		log.info("\n耗时：{}" + (System.currentTimeMillis() - stime) + "秒");
		return sr;
	}

	public TbSpShare saveShare(String userCode) {
		Md5PwdEncoder md5PwdEncoder = new Md5PwdEncoder();
		// 加密密码
		String shareId = md5PwdEncoder.encodePassword(userCode + ":1");
		List<TbSpShare> tsList = shareDao.findByShareId(shareId);
		if (CollectionUtils.isEmpty(tsList)) {
			TbSpShare addTbSp = new TbSpShare();
			addTbSp.setShareId(shareId);
			addTbSp.setChannelName("");
			addTbSp.setSaleCode("");
			addTbSp.setSaleName("");
			addTbSp.setLastShareType("");
			addTbSp.setState(TbSpShare.SHARE_TYPE_NO_VISIT);
			addTbSp.setUserCodeChain("");
			addTbSp.setUserCode(userCode);
			addTbSp.setProductId("店铺-自动生成");
			addTbSp.setShareType("店铺-自动生成");
			addTbSp.setSharinChain(0);
			addTbSp.setCreateTime(new Date());
			return shareDao.save(addTbSp);
		}
		return null;
	}
	// private String strings =
	// "[{\"name\":\"广东恒华保险代理有限公司\",\"nickName\":\"广东恒华保险代理有限公司\",\"idNumber\":\"500237199206160000\",\"mobile\":\"44000001001\"},{\"name\":\"广东恒华保险代理有限公司\",\"nickName\":\"广东恒华保险代理有限公司\",\"idNumber\":\"500237199206160000\",\"mobile\":\"44000001002\"},
	// {\"name\":\"广东恒华保险代理有限公司\",\"nickName\":\"广东恒华保险代理有限公司\",\"idNumber\":\"500237199206160000\",\"mobile\":\"44000001003\"},{\"name\":\"广东恒华保险代理有限公司\",\"nickName\":\"广东恒华保险代理有限公司\",\"idNumber\":\"500237199206160000\",\"mobile\":\"44000001004\"}]";

	public String userJsons = "[]";
}
